package com.bw.paper.mvp.view.Activity;

import android.Manifest;
import android.os.Build;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.blankj.utilcode.util.LogUtils;
import com.bw.paper.App;
import com.bw.paper.R;
import com.bw.paper.entity.CommentEntity;
import com.bw.paper.entity.UserEntity;
import com.bw.paper.mvp.base.model.BaseEntity;
import com.bw.paper.mvp.base.view.BaseActivity;
import com.bw.paper.mvp.contact.LREContract;
import com.bw.paper.mvp.di.DaggerLREComponent;
import com.bw.paper.mvp.di.LREModules;
import com.bw.paper.mvp.model.HttpCode;
import com.bw.paper.mvp.presenter.LREPresenter;
import com.bw.paper.mvp.view.Fragment.news.Adapter.CommentAdapter;
import com.bw.paper.utils.ToastUtils;
import com.bw.paper.widget.x5.X5WebView;
import com.google.android.material.appbar.AppBarLayout;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.tb.emoji.Emoji;
import com.tb.emoji.EmojiUtil;
import com.tb.emoji.FaceFragment;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class NewsValuesActivity extends BaseActivity<LREPresenter>
        implements LREContract.ILREView,View.OnClickListener
        ,FaceFragment.OnEmojiClickListener, AppBarLayout.OnOffsetChangedListener ,
        OnRefreshLoadMoreListener {

    private int num=1;
    private ImageView head_back_img;
    private AppBarLayout web_values_appbar;
    private TextView live_msg_num_tv;
    private RelativeLayout live_msg_relative;
    private X5WebView web_values_x5;
    private RecyclerView web_values_comment_rv;
    private SmartRefreshLayout web_values_comment_sm;
    private RelativeLayout live_edt_btn;//开启输入框
    private ImageView live_face_img;//显示表情包
    private ImageView live_emoji_img;//输入系统显示表情
    private RelativeLayout live_bottom_view;//输入系统整体布局
    private LinearLayout live_emoji_linear;//表情系统布局
    private EditText live_msg_edt;
    private ImageView live_collection_img;

    private TextView live_send_tv;//发送按钮
    private View headView;
    private CommentAdapter commentAdapter;
    private long news_id = 0;
    private String news_url;
    private boolean appFlag = true;//当前界面中appbarlayout展开以及折叠标志,fasle折叠true展开
    private boolean flag = false;

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (R.id.live_edt_btn == id){
            live_bottom_view.setVisibility(View.VISIBLE);
            live_emoji_linear.setVisibility(View.GONE);
        }else if (R.id.live_face_img == id){
            live_bottom_view.setVisibility(View.VISIBLE);
            live_emoji_linear.setVisibility(View.VISIBLE);
        }else if (R.id.live_emoji_img == id){
            if (live_emoji_linear.getVisibility() == View.VISIBLE){
                //当前正在显示表情系统->隐藏掉表情布局
                live_emoji_linear.setVisibility(View.GONE);
                live_emoji_img.setImageResource(R.drawable.res_7icon_129);
            }else {
                //当前正在隐藏表情系统->显示表情布局
                live_emoji_linear.setVisibility(View.VISIBLE);
                live_emoji_img.setImageResource(R.drawable.res_7icon_131);
            }
        }else if (R.id.live_send_tv == id){
            if (live_msg_edt.getText() == null){
                ToastUtils.showMsg("请输入评论内容");
                return;
            }
            if (live_msg_edt.getText().toString().isEmpty()){
                ToastUtils.showMsg("请输入评论内容");
                return;
            }
            UserEntity entity = App.getInstance().getDaoSession().queryBuilder(UserEntity.class)
                    .list().get(0);
            Map<String,Object>map = new HashMap<>();
            map.put("code",HttpCode.ADDCOMMENTCODE);
            map.put("comment_address",mycity);
            map.put("comment_time",System.currentTimeMillis()/1000);
            map.put("comment_value",live_msg_edt.getText().toString());
            map.put("news_id",news_id);
            map.put("user_id",entity.user_id);
            //发布评论
            p.requestAll(map);

        }else if (R.id.head_back_img == id){
            finish();
        }else if (R.id.live_msg_relative == id){
            if (appFlag){
                live_msg_num_tv.setText("正文");
            }else {
                live_msg_num_tv.setText(""+937);
            }
            appFlag = !appFlag;
            web_values_appbar.setExpanded(appFlag);
        }else
             if (R.id.live_collection_img == id) {
                 try {
                     UserEntity userEntity = App.getInstance().getDaoSession().queryBuilder(UserEntity.class).list().get(0);
                     if (!flag) {
                         Map<String, Object> map = new HashMap<>();
                         map.put("code", HttpCode.ADDCollectNewsCODE);
                         map.put("news_id", news_id);
                         map.put("user_id", userEntity.getUser_id());
                         p.requestAll(map);
                         flag = true;
                     } else {
                         Map<String, Object> map = new HashMap<>();
                         map.put("code", HttpCode.DELCollectNewsCODE);
                         map.put("news_id", news_id);
                         map.put("user_id", userEntity.getUser_id());
                         p.requestAll(map);
                         flag = false;
                     }
                 } catch (Exception e) {
                     e.printStackTrace();
                 }

        }
//

    }

    @Override
    public View addStatusView() {
        return f(R.id.web_values_root);
    }

    @Override
    public int bindlayout() {
        return R.layout.activity_news_values;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void initView() {
        requestPermissions(new String[]{
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        },111);

        initLocationOption();
        headView = LayoutInflater.from(this).inflate(R.layout.view_web_values,null);
        news_url = getIntent().getExtras().getString("news_url");
        news_id = getIntent().getExtras().getLong("news_id",0);
        web_values_appbar = f(R.id.web_values_appbar);
        live_msg_relative = f(R.id.live_msg_relative);
        live_msg_num_tv = f(R.id.live_msg_num_tv);
        head_back_img = f(R.id.head_back_img);
        web_values_x5 = f(R.id.web_values_x5);
        live_edt_btn = f(R.id.live_edt_btn);
        live_face_img = f(R.id.live_face_img);
        live_collection_img = f(R.id.live_collection_img);
        live_bottom_view = f(R.id.live_bottom_view);
        live_emoji_linear = f(R.id.live_emoji_linear);
        live_emoji_img = f(R.id.live_emoji_img);
        live_send_tv = f(R.id.live_send_tv);
        live_msg_edt = f(R.id.live_msg_edt);
        web_values_comment_rv = f(R.id.web_values_comment_rv);
        web_values_comment_sm = f(R.id.web_values_comment_sm);

        web_values_comment_sm.setEnableRefresh(true);
        web_values_comment_sm.setEnableLoadMore(true);
        web_values_comment_sm.setRefreshHeader(new ClassicsHeader(this));
        web_values_comment_sm.setRefreshFooter(new ClassicsFooter(this));
        web_values_comment_sm.setOnRefreshLoadMoreListener(this);

        web_values_x5.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String s) {
                if (!s.contentEquals("http://118.195.161.134:8066/"))
                    return true;
                return false;
            }
        });

        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();

        option.setIsNeedAddress(true);
//可选，是否需要地址信息，默认为不需要，即参数为false
//如果开发者需要获得当前点的地址信息，此处必须为true

        option.setNeedNewVersionRgc(true);
//可选，设置是否需要最新版本的地址信息。默认需要，即参数为true

        mLocationClient.setLocOption(option);
//mLocationClient为第二步初始化过的LocationClient对象
//需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
//更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明


        getSupportFragmentManager().beginTransaction().add(R.id.live_emoji_linear,
                FaceFragment.Instance()).commit();
        web_values_x5.loadUrl(news_url);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        web_values_comment_rv.setLayoutManager(manager);
        commentAdapter = new CommentAdapter();
        commentAdapter.setEmptyView(R.layout.view_empty);
        commentAdapter.addHeaderView(headView);
        web_values_comment_rv.setAdapter(commentAdapter);

        live_edt_btn.setOnClickListener(this::onClick);
        live_face_img.setOnClickListener(this::onClick);
        live_emoji_img.setOnClickListener(this::onClick);
        live_send_tv.setOnClickListener(this::onClick);
        head_back_img.setOnClickListener(this::onClick);
        live_msg_relative.setOnClickListener(this::onClick);
        web_values_appbar.addOnOffsetChangedListener(this);
        live_collection_img.setOnClickListener(this);
    }
    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location){
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取地址相关的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

            String addr = location.getAddrStr();    //获取详细地址信息
            String country = location.getCountry();    //获取国家
            String province = location.getProvince();    //获取省份
            String city = location.getCity();    //获取城市
            String district = location.getDistrict();    //获取区县
            String street = location.getStreet();    //获取街道信息
            String adcode = location.getAdCode();    //获取adcode
            String town = location.getTown();    //获取乡镇信息
            mycity = city;
            LogUtils.json(mycity);
        }
    }

    private void initLocationOption() {
//定位服务的客户端。宿主程序在客户端声明此类，并调用，目前只支持在主线程中启动
        LocationClient locationClient = new LocationClient(getApplicationContext());
//声明LocationClient类实例并配置定位参数
        LocationClientOption locationOption = new LocationClientOption();
        MyLocationListener myLocationListener = new MyLocationListener();
//注册监听函数
        locationClient.registerLocationListener(myLocationListener);
//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        locationOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
//可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
        locationOption.setCoorType("gcj02");
//可选，默认0，即仅定位一次，设置发起连续定位请求的间隔需要大于等于1000ms才是有效的
        locationOption.setScanSpan(1000);
//可选，设置是否需要地址信息，默认不需要
        locationOption.setIsNeedAddress(true);
//可选，设置是否需要地址描述
        locationOption.setIsNeedLocationDescribe(true);
//可选，设置是否需要设备方向结果
        locationOption.setNeedDeviceDirect(false);
//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        locationOption.setLocationNotify(true);
//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        locationOption.setIgnoreKillProcess(true);
//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        locationOption.setIsNeedLocationDescribe(true);
//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        locationOption.setIsNeedLocationPoiList(true);
//可选，默认false，设置是否收集CRASH信息，默认收集
        locationOption.SetIgnoreCacheException(false);
//可选，默认false，设置是否开启Gps定位
        locationOption.setOpenGps(true);
//可选，默认false，设置定位时是否需要海拔信息，默认不需要，除基础定位版本都可用
        locationOption.setIsNeedAltitude(false);
//设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者，该模式下开发者无需再关心定位间隔是多少，定位SDK本身发现位置变化就会及时回调给开发者
        locationOption.setOpenAutoNotifyMode();
//设置打开自动回调位置模式，该开关打开后，期间只要定位SDK检测到位置变化就会主动回调给开发者
        locationOption.setOpenAutoNotifyMode(3000, 1, LocationClientOption.LOC_SENSITIVITY_HIGHT);
//需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        locationClient.setLocOption(locationOption);
//开始定位
        locationClient.start();
    }

    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private String mycity;
    //BDAbstractLocationListener为7.2版本新增的Abstract类型的监听接口
//原有BDLocationListener接口暂时同步保留。具体介绍请参考后文中的说明


    @Override
    public void initData() {
        Map<String ,Object>map = new HashMap<>();
        map.put("code", HttpCode.SELCOMMENTCODE);
        map.put("news_id",news_id);
        p.requestAll(map);

        try {
            UserEntity  userEntity = App.getInstance().getDaoSession().queryBuilder(UserEntity.class).list().get(0);
            Map<String, Object> map1 = new HashMap<>();
            map1.put("code", HttpCode.ISCollectNewsCODE);
            map1.put("news_id", news_id);
            map1.put("user_id", userEntity.getUser_id());
            p.requestAll(map1);
        } catch (Exception e) {
            e.printStackTrace();
        }



    }

    @Override
    public void inject() {
        DaggerLREComponent.builder().lREModules(new LREModules(this))
                .build().injectNewsValuesActivity(this);
    }
    @Override
    public void refreshAll(BaseEntity entity) {
        if (entity instanceof CommentEntity){
            CommentEntity commentEntity = (CommentEntity) entity;
            commentAdapter.setNewInstance(commentEntity.getValues());
        }
        else {
            if (entity.message.equals("发表成功")){
                //当前评论发布成功
                //清空输入框
                live_msg_edt.setText("");
                //刷新评论列表数据
                //请求获取最新评论列表
//                initData();
            }
        }
        if (entity.message.equals("收藏成功")) {
            ToastUtils.showMsg("收藏成功");
            live_collection_img.setImageResource(R.drawable.res_7icon_139);
        } else if (entity.message.equals("取消收藏成功")) {
            ToastUtils.showMsg("取消收藏成功");
            live_collection_img.setImageResource(R.drawable.res_7icon_128);
        }
        if (entity.message.equals("成功")) {
            live_collection_img.setImageResource(R.drawable.res_7icon_139);
            flag = true;
        } else if (entity.message.equals("失败")) {
            live_collection_img.setImageResource(R.drawable.res_7icon_128);
            flag = false;
        }


    }

    @Override
    public void refreshRecyckerView(BaseEntity entity) {
        CommentEntity commentEntity = (CommentEntity) entity;
        commentAdapter.setNewInstance(commentEntity.getValues());
    }

    @Override
    public void loadMoreRecyclerView(BaseEntity entity) {
        CommentEntity commentEntity = (CommentEntity) entity;
        if (commentEntity.getValues()==null){
            ToastUtils.showMsg("已加载全部");
            return;
        }
        if (commentEntity.getValues().size() == 0){
            ToastUtils.showMsg("已加载全部");
            return;
        }
        commentAdapter.addData(commentEntity.getValues());
    }

    @Override
    public void onEmojiDelete() {
        String text = live_msg_edt.getText().toString();
        if (text.isEmpty()) {
            return;
        }
        if ("]".equals(text.substring(text.length() - 1, text.length()))) {
            int index = text.lastIndexOf("[");
            if (index == -1) {
                int action = KeyEvent.ACTION_DOWN;
                int code = KeyEvent.KEYCODE_DEL;
                KeyEvent event = new KeyEvent(action, code);
                live_msg_edt.onKeyDown(KeyEvent.KEYCODE_DEL, event);
                try {
                    EmojiUtil.handlerEmojiText(live_msg_edt, live_msg_edt.getText().toString(), this);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return;
            }
            live_msg_edt.getText().delete(index, text.length());
            try {
                EmojiUtil.handlerEmojiText(live_msg_edt, live_msg_edt.getText().toString(), this);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        int action = KeyEvent.ACTION_DOWN;
        int code = KeyEvent.KEYCODE_DEL;
        KeyEvent event = new KeyEvent(action, code);
        live_msg_edt.onKeyDown(KeyEvent.KEYCODE_DEL, event);
        try {
            EmojiUtil.handlerEmojiText(live_msg_edt, live_msg_edt.getText().toString(), this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            if (live_bottom_view.getVisibility() == View.VISIBLE){
                live_bottom_view.setVisibility(View.GONE);
            }else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onEmojiClick(Emoji emoji) {
        if (emoji != null) {
            int index = live_msg_edt.getSelectionStart();
            Editable editable = live_msg_edt.getEditableText();
            if (index < 0) {
                editable.append(emoji.getContent());
            } else {
                editable.insert(index, emoji.getContent());
            }
            try {
                EmojiUtil.handlerEmojiText(live_msg_edt, live_msg_edt.getText().toString(), this);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private int oldverticalOffset;

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
//        LogUtils.show("onOffsetChanged:"+verticalOffset);
        if (oldverticalOffset==verticalOffset)
            return;
        if (verticalOffset==0){
            //当前显示正文
            appFlag = true;
            live_msg_num_tv.setText(""+937);
        }else {
            appFlag = false;
            live_msg_num_tv.setText("正文");
        }
        oldverticalOffset = verticalOffset;
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.finishLoadMore();
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpCode.SELCOMMENTCODE);
        map.put("news_id",news_id);
        p.requestLoad(map);

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshLayout.finishRefresh();
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpCode.SELCOMMENTCODE);
        map.put("news_id", news_id);
        p.requestRefresh(map);
    }
}